package com.sso.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sso.entity.Maps;
import com.sso.entity.MapsRes;
import com.sso.entity.Sample;
import com.sso.entity.Task;
import com.sso.filter.R;
import com.sso.service.MapsResService;
import com.sso.service.MapsService;
import com.sso.service.SampleService;
import com.sso.service.TaskService;
import com.sso.utils.FileUtil;
import com.sso.utils.MyProperty;
import com.sso.utils.ZipUtil;
import com.sso.utils.ZipUtil2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xia
 * @since 2022-07-23
 */

@RestController
@Slf4j
@CrossOrigin
@Api(tags = "Maps接口")
@RequestMapping("/shale_porosity/maps")
public class MapsController {
    @Autowired
    private MyProperty myProperty;
    @Autowired
    private MapsService mapsService;
    @Autowired
    MapsResService mapsResService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private SampleService sampleService;
    @GetMapping("move")
    @ApiOperation("无用")
    public R move(String from, String to){
        File file=new File(from);
        File file1=new File(to);
        try {
            FileUtils.moveDirectory(file,file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }
    @GetMapping("file")
    @ApiOperation("maps原文件地址")
    public R wjian(Integer id){
        Maps one = mapsService.getOne(new LambdaQueryWrapper<Maps>().eq(Maps::getSampleId, id));
        return R.ok().put("maps",one.getPath()+"/SE2_files");
    }

    @PostMapping(value = "/Maps")
    @ApiOperation("上传Maps")
    public R uploadMaps(@RequestPart("files") MultipartFile files,Integer sampleId) {
        int id=sampleId;
        Maps one = mapsService.getOne(new LambdaQueryWrapper<Maps>().eq(Maps::getSampleId, id));
        if(one!=null){
            return R.error("已经上传");
        }
        String a=null;
            // 判断文件后缀是否为zip
            a=files.getOriginalFilename();
            log.info("上传文件名称 {} ,判断后缀是否为.zip",files.getOriginalFilename());
            String suffix = Objects.requireNonNull(files.getOriginalFilename()).substring(files.getOriginalFilename().lastIndexOf(".") + 1);
            if(!"ZIP".equals(suffix.toUpperCase())){
                return R.error("上传文件不是.zip结尾,Maps只能上传压缩包");
            }
        String path=myProperty.getMapsPath()+UUID.randomUUID().toString();
        String pathNm=myProperty.getMapsPath()+"10nm";
        File filePath=new File(path);
        File file1=new File(pathNm);
        try {
            FileUtils.copyDirectory(file1,filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        R r = FileUtil.uploadFile(files, path+"/data/MAPS2/data/1478130726/");
        String url = (String)r.get("url");
        if(StringUtils.isEmpty(url)){
            return R.error("上传maps错误，请重试");
        }
        String srcFile =url;
        try {
            ZipUtil.deCompress(srcFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error(400,"文件上传失败");
        }
        String res = url.replace(".zip","");
        res=res.replace("/home/text2","");
        Sample byId = sampleService.getById(id);
        byId.setMaps(1);
        sampleService.updateById(byId);
        Maps maps=new Maps();
        maps.setPath(res);
        maps.setSampleId(id);
        mapsService.save(maps);
        return R.ok();
    }
    @PostMapping(value = "/size")
    @ApiOperation("添加比例尺")
    public R size(Integer id,Integer size){
        Maps one = mapsService.getOne(new LambdaQueryWrapper<Maps>().eq(Maps::getSampleId, id));
        one.setSize(size);
        mapsService.updateById(one);
        return R.ok();
    }
    @PostMapping("/MapsUpdate")
    @ApiOperation("重新上传")
    public R uploadMaps1(@RequestPart("files") MultipartFile files,Integer id) {
        Maps one = mapsService.getOne(new LambdaQueryWrapper<Maps>().eq(Maps::getSampleId, id));
        if(one==null) {
            return R.error("未上传");
        }
        if(taskService.getOne(new LambdaQueryWrapper<Task>().eq(Task::getPictureId,id).eq(Task::getTaskType,1))!=null){
            return R.error("已经运行，不能进行该操作");
        }
        File file3=new File(myProperty.getPath()+one.getPath());
        file3.delete();
        mapsService.removeById(one.getId());
        String a=null;
            // 判断文件后缀是否为zip
            a=files.getOriginalFilename();
            log.info("上传文件名称 {} ,判断后缀是否为.zip",files.getOriginalFilename());
            String suffix = Objects.requireNonNull(files.getOriginalFilename()).substring(files.getOriginalFilename().lastIndexOf(".") + 1);
            if(!"ZIP".equals(suffix.toUpperCase())){
                return R.error("上传文件不是.zip结尾,Maps只能上传压缩包");
            }
        String path=myProperty.getMapsPath()+UUID.randomUUID().toString();
        String pathNm=myProperty.getMapsPath()+"10nm";
        File filePath=new File(path);
        File file1=new File(pathNm);
        try {
            FileUtils.copyDirectory(file1,filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        R r = FileUtil.uploadFile(files, path+"/data/MAPS2/data/1478130726/");
        String url = (String)r.get("url");
        if(StringUtils.isEmpty(url)){
            return R.error("上传maps错误，请重试");
        }
        String srcFile =url;
        try {
            ZipUtil.deCompress(srcFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error(400,"文件上传失败");
        }
        String res = url.replace(".zip","");
        res=res.replace("/home/text2","");
        Sample byId = sampleService.getById(id);
        byId.setMaps(1);
        sampleService.updateById(byId);
        Maps maps=new Maps();
        maps.setPath(res);
        maps.setSampleId(id);
        mapsService.save(maps);
        return R.ok();
    }

    @GetMapping("display/{id}")
    @ApiOperation("通过样品id展示结果")
    public R display(@PathVariable Long id){
        List<Maps> list = mapsService.list(new QueryWrapper<Maps>().lambda()
                .eq(Maps::getSampleId, id));
        List<MapsRes> list1 = mapsResService.list(new QueryWrapper<MapsRes>().lambda()
                .eq(MapsRes::getMapsId, list.get(0).getId()));
        String path = list.get(0).getPath();
        path=path.replace("shale_porosity/","");
        path=path.replace("/data/1478130726/SE2","")+"/index.html";
        return R.ok().put("path",path);
    }

    @GetMapping("contrast/{id}")
    @ApiOperation("通过样品id展示对比结果")
    public R contrast(@PathVariable Long id){
        List<Maps> list = mapsService.list(new QueryWrapper<Maps>().lambda()
                .eq(Maps::getSampleId, id));
        List<MapsRes> list1 = mapsResService.list(new QueryWrapper<MapsRes>().lambda()
                .eq(MapsRes::getMapsId, list.get(0).getId()));
        String path = list.get(0).getPath();
        path=path.replace("/data/MAPS2/data/1478130726/SE2","")+"/index.html";
        path=path.replace("shale_porosity/","");
        return R.ok().put("path",path);
    }

    @GetMapping("/downloadMaps")
    public R download(Integer id) throws IOException {
        Sample byId1 = sampleService.getById(id);
        List<Maps> list = mapsService.list(new QueryWrapper<Maps>().lambda()
                .eq(Maps::getSampleId, id));
        String replace1 = list.get(0).getPath().replace("/data/MAPS2/data/1478130726/SE2", "");
        replace1=replace1.replace("shale_porosity/","");
        replace1=replace1+".zip";
        return R.ok().put("path",replace1);
    }

    @Transactional
    @DeleteMapping("/{id}")
    @ApiOperation("删除Maps")
    public R delUser(@PathVariable Long id) {
        List<Maps> list = mapsService.list(new QueryWrapper<Maps>().lambda()
                .eq(Maps::getSampleId, id));
        if(list.isEmpty()){
            return R.ok();
        }
        String replace1 = list.get(0).getPath().replace("/data/MAPS2/data/1478130726/SE2", "");
        String path=myProperty.getPath()+replace1;
        String path2=path+".zip";
        File file=new File(path);
        if(file.exists()){
            FileUtil.deleteFiles(file);
        }
        File file1=new File(path2);
        if(file.exists()){
            FileUtil.deleteFiles(file1);
        }
        mapsService.removeById(list.get(0).getId());
        Integer mapsRes=list.get(0).getId();
        MapsRes one = mapsResService.getOne(new LambdaQueryWrapper<MapsRes>().eq(MapsRes::getMapsId, mapsRes));
        if(one!=null){
            mapsResService.removeById(one.getId());
        }
        return R.ok();
    }

    @PostMapping("/gap")
    @ApiOperation("孔缝分类")
    public R gapClassification(@RequestParam Integer pictureId) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Task::getPictureId, pictureId)
                .eq(Task::getTaskType, 1);
        Task task = taskService.getOne(queryWrapper);
        if(task!=null) {
            if (task.getTaskStatus() == 2) {
                return R.ok("结果已返回").put("TaskId", 2);
            }
            else if(task.getTaskStatus()==1){
                return R.ok("算法正在执行，请稍等");
            }else {
                taskService.removeById(task.getId());
            }
        }
        Maps one = mapsService.getOne(new LambdaQueryWrapper<Maps>().eq(Maps::getSampleId, pictureId));
        String path=one.getPath();
        path=path.replace("shale_porosity/data/","");
        return mapsService.gapClassification(pictureId, path);
    }

    @PostMapping("/mineral")
    @ApiOperation("矿物提取")
    public R gapClassification1(@RequestParam Integer pictureId) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Task::getPictureId, pictureId)
                .eq(Task::getTaskType, 2);
        Task task = taskService.getOne(queryWrapper);
        if(task!=null) {
            if (task.getTaskStatus() == 2) {
                return R.ok("结果已返回").put("TaskId", 2);
            }
            else if(task.getTaskStatus()==1){
                return R.ok("算法正在执行，请稍等");
            }else {
                taskService.removeById(task.getId());
            }
        }
        Maps one = mapsService.getOne(new LambdaQueryWrapper<Maps>().eq(Maps::getSampleId, pictureId));
        String path=one.getPath();
        path=path.replace("shale_porosity/data/","");
        return mapsService.gapClassification1(pictureId, path);
    }
}
